package com.eischet.lookup.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import org.apache.log4j.Logger;

import static com.eischet.lookup.Functional.splitString;

/**
 * Created with IntelliJ IDEA.
 * User: stefan
 * Date: 24.05.12
 * Time: 18:38
 * To change this template use File | Settings | File Templates.
 */
public class TimestampLoader implements Runnable {

    private final static Logger logger = Logger.getLogger(TimestampLoader.class);

    private WebApplication application;
    private SearchIndex index;

    public void setApplication(WebApplication application) {
        this.application = application;
    }

    public void setIndex(SearchIndex index) {
        this.index = index;
    }

    @Override
    public void run() {
        long ts = getMostRecentWatermark();
        logger.info("updated most recent watermark: " + ts);
        application.setMostRecentWatermark(ts);
    }

    private long getMostRecentWatermark() {
        long result = 0;
        String watermarksPath = index.getPath() + File.separator + ".." + File.separator + "watermarks.ini";
        try {
            FileReader fileReader = new FileReader(watermarksPath);
            BufferedReader reader = new BufferedReader(fileReader);
            try {
                int lineNumber = 0;
                while (true) {
                    String line = reader.readLine();
                    if (line == null) {
                        break;
                    }
                    ++lineNumber;
                    List<String> parts = splitString(line.trim(), ":", 2);
                    try {
                        String type = parts.get(0);
                        String idWs = parts.get(1);
                        Long tsWs = Long.parseLong(parts.get(2), 10);
                        if (tsWs > result) {
                            result = tsWs;
                        }
                    } catch (Exception ex) {
                        logger.warn(String.format("loadWatermarks: syntax error in %s:%d, '%s'", watermarksPath, lineNumber, line), ex);
                    }
                }
            } finally {
                reader.close();
                fileReader.close();
            }
        } catch (FileNotFoundException ex) {
            logger.info(String.format("loadWatermarks: file '%s' not found, a new one will be created while indexing", watermarksPath));
        } catch (Exception ex) {
            logger.warn(String.format("loadWatermarks: error loading %s", watermarksPath), ex);
        }
        return result;
    }
}
